package com.moran.test.akk.http

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.Http.ServerBinding
import akka.stream.ActorMaterializer
import org.slf4j.LoggerFactory

import scala.concurrent.{ExecutionContextExecutor, Future}
import scala.util.{Failure, Success}

import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route


object HelloWorld extends App{
  private[this] val log = LoggerFactory.getLogger(getClass.getName)

  implicit val theSystem: ActorSystem = ActorSystem("akka-http-starter")
  implicit val materialize: ActorMaterializer = ActorMaterializer()
  implicit val ec: ExecutionContextExecutor = theSystem.dispatcher

  object ApplicationRoute {
    def route: Route =
      pathPrefix("name") {
        get {
          parameter("name") { (name) =>
            complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "Hello!"+name))
          }
        }

      }
  }


  val (host, port) = ("127.0.0.1",9999)
  val handler = ApplicationRoute.route

  val bindingFuture: Future[ServerBinding] =
    Http().bindAndHandle(handler, host, port)

  bindingFuture.onComplete {
    case Success(binding) =>
      log.info(s"Bind success: $binding")
    case Failure(_) =>
      log.error(s"Failed to bind to {}:{}!",host,port)
      System.exit(-1)
  }
}
